package com.tensquare.article.controller;

import com.baomidou.mybatisplus.plugins.Page;
import com.tensquare.article.pojo.Article;
import com.tensquare.article.service.ArticleService;
import entity.PageResult;
import entity.Result;
import entity.StatusCode;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

/**
 * @Author : 残影
 * @Date: 2020/7/23 14:05
 */
@RestController
@RequestMapping("/article")
@CrossOrigin
@Api(tags = "文章模块")
public class ArticleController {
    @Autowired
    private ArticleService articleService;

    @GetMapping("/exception")
    @ApiOperation("测试公共异常处理")
    public Result test() {
        int a = 1 / 0;
        return null;
    }

    /**
     * 之前接受文章数据，使用pojo，但是现在根据条件查询
     * 而所有的条件都需要进行判断，遍历pojo的所有属性需要使用反射的方式，成本较高，性能较低
     * 直接使用集合的方式遍历，这里接受数据改为Map集合
     */
    @PostMapping("/search/{page}/{size}")
    @ApiOperation("文章分页")
    public Result findByPage(@PathVariable Integer page, @PathVariable Integer size,
                             @RequestBody Map<String, Object> map) {
        //根据条件分页查询
        Page<Article> pageData = articleService.findByPage(map, page, size);
        //封装分页返回对象
        PageResult<Article> pageResult = new PageResult<>(
                pageData.getTotal(), pageData.getRecords()
        );
        //返回数据
        return new Result(true, StatusCode.OK, "查询成功", pageResult);
    }

    @DeleteMapping("/{articleId}")
    @ApiOperation("根据ID删除文章")
    public Result deleteById(@PathVariable String articleId) {
        articleService.deleteById(articleId);
        return new Result(true, StatusCode.OK, "删除成功");
    }


    @PutMapping("/{articleId}")
    @ApiOperation("修改文章")
    public Result updateById(@PathVariable String articleId, @RequestBody Article article) {
        //设置id
        article.setId(articleId);
        // 执行修改
        articleService.updateById(article);
        return new Result(true, StatusCode.OK, "修改成功");
    }

    @PostMapping()
    @ApiOperation("增加文章")
    public Result save(@RequestBody Article article) {
        articleService.save(article);
        return new Result(true, StatusCode.OK, "新增成功");
    }

    @GetMapping("/{articleId}")
    @ApiOperation("根据ID查询文章")
    public Result findById(@PathVariable String articleId) {
        Article article = articleService.findById(articleId);
        return new Result(true, StatusCode.OK, "查询成功", article);
    }

    @GetMapping()
    @ApiOperation("文章全部列表")
    public Result findAll() {
        List<Article> list = articleService.findAll();
        return new Result(true, StatusCode.OK, "查询成功", list);
    }
}
